echo_station = {
	name = "Echo of Moscow",

	url_main = "http://www.echo.msk.ru/programs/",
	url_live = "http://w02-sw01.akadostream.ru:8000/moscowecho128.mp3",
	rss_file = "rss-audio.xml",
}

echo_dirs = {
	tmp_dir = "~/.tmp_echomsk_files",
	tmp_file_urls = "/home/debmaster/.tmp_echomsk_files/tmp_echo_urls",
	tmp_file_names= "/home/debmaster/.tmp_echomsk_files/tmp_names"
}

player_mplayer = {
	player = "/usr/bin/mplayer",
	options = "-really-quiet cache 16000"
}

echo_listener = {
	station = echo_station,
	player = player_mplayer,
	dirs = echo_dirs,
	programms = {}
}

function get_grog_list (l)

	local ind = 1;
	l.programms = {}

	print (l.station.name)

	print ("получение списка программ...")
	os.execute("./mecho_names.sh > " .. l.dirs.tmp_file_names)
	print ("Готово!\n")

	io.input(tostring(l.dirs.tmp_file_names))

	for line in io.lines() do 
		words = {}
		string.gsub(line, "(%a+)", function (w)
		      table.insert(words, w)
			      end)
		w = words[1]
		n = string.gsub(line, ".+%s%-%s", "")
		u = l.station.url_main .. w .. "/" .. l.station.rss_file

		l.programms[ind] = {word = w, name = n, url = u}

		ind = ind + 1
	end
end 

function print_progs (l)
	for i, v in ipairs (l.programms) do
		print (i, v.name)
	end 
end 

function in_prog (l, num)
	if l.programms[num] == nil then
		print("Программа отсутствует")
		return 
	end
	print ("Название программы:", l.programms[num].name)
	print ("Сылка:", l.programms[num].url)
	print ()

	get_mp3_urls(l, num)
	print ("Ссылки к трекам:")
	for i, v in pairs (l.programms[num].track) do
		print (i, v)
	end

	flag = true 
	while flag do 
		io.input(io.stdin)
		io.write("Трек: ")
		prnr = io.read("*number")
		if prnr == nil or prnr == 0 then 
			break 
		end 
		
		play_url(l, l.programms[num].track[prnr])
		print()
	end 
	print()
end

function play_url (l, u)
	local cmd = l.player.player .. " '" .. u .. "' "
	print (cmd)
 	os.execute(cmd)
end 

function get_mp3_urls (l, n)
	local url = l.programms[n].url
	local tfl = l.dirs.tmp_file_urls

	local cmd = "curl --silent " .. url .. " | grep .mp3 | ./cut-urls > " .. tfl
 	os.execute(cmd)
 	os.execute("sync")
	io.input(tostring(tfl))
	l.programms[n].track = {}
	local i = 1
	for line in io.lines() do
		l.programms[n].track[i] = line
		i = i + 1
	end
end 

get_grog_list(echo_listener)
print_progs (echo_listener)

print ()

prnr = 1
while prnr do 
	io.input(io.stdin)
	io.write("Number: ")
	prnr = io.read("*number")
	if prnr == nil or prnr == 0 then 
		break 
	end
	in_prog (echo_listener, prnr)
end
